package com.ruoyi.ism.service.impl;

import java.util.List;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.ism.domain.IsmIntegralRecord;
import com.ruoyi.ism.mapper.IsmIntegralRecordMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.ism.mapper.IsmCustManageMapper;
import com.ruoyi.ism.domain.IsmCustManage;
import com.ruoyi.ism.service.IIsmCustManageService;

import javax.validation.Validator;

/**
 * 客户管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-07-19
 */
@Service
public class IsmCustManageServiceImpl implements IIsmCustManageService
{
    private static final Logger log = LoggerFactory.getLogger(IsmCustManageServiceImpl.class);

    @Autowired
    private IsmCustManageMapper ismCustManageMapper;

    @Autowired
    private IsmIntegralRecordMapper ismIntegralRecordMapper;

    @Autowired
    protected Validator validator;

    /**
     * 查询客户管理
     * 
     * @param custId 客户管理主键
     * @return 客户管理
     */
    @Override
    public IsmCustManage selectIsmCustManageByCustId(Long custId)
    {
        return ismCustManageMapper.selectIsmCustManageByCustId(custId);
    }

    /**
     * 查询客户管理列表
     * 
     * @param ismCustManage 客户管理
     * @return 客户管理
     */
    @Override
    public List<IsmCustManage> selectIsmCustManageList(IsmCustManage ismCustManage)
    {
        return ismCustManageMapper.selectIsmCustManageList(ismCustManage);
    }

    /**
     * 新增客户管理
     * 
     * @param ismCustManage 客户管理
     * @return 结果
     */
    @Override
    public int insertIsmCustManage(IsmCustManage ismCustManage)
    {
        ismCustManage.setCreateTime(DateUtils.getNowDate());
        return ismCustManageMapper.insertIsmCustManage(ismCustManage);
    }

    /**
     * 修改客户管理
     * 
     * @param ismCustManage 客户管理
     * @return 结果
     */
    @Override
    public int updateIsmCustManage(IsmCustManage ismCustManage)
    {
        ismCustManage.setUpdateTime(DateUtils.getNowDate());
        return ismCustManageMapper.updateIsmCustManage(ismCustManage);
    }

    /**
     * 批量删除客户管理
     * 
     * @param custIds 需要删除的客户管理主键
     * @return 结果
     */
    @Override
    public int deleteIsmCustManageByCustIds(Long[] custIds)
    {
        return ismCustManageMapper.deleteIsmCustManageByCustIds(custIds);
    }

    /**
     * 删除客户管理信息
     * 
     * @param custId 客户管理主键
     * @return 结果
     */
    @Override
    public int deleteIsmCustManageByCustId(Long custId)
    {
        return ismCustManageMapper.deleteIsmCustManageByCustId(custId);
    }

    /**
     * 导入用户数据
     *
     * @param userList 用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importCustManage(List<IsmCustManage> userList, Boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(userList) || userList.size() == 0)
        {
            throw new ServiceException("导入客户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        //String password = configService.selectConfigByKey("sys.user.initPassword");
        for (IsmCustManage ismCustManage : userList)
        {
            try
            {
                // 验证是否存在这个客户
                IsmCustManage u = ismCustManageMapper.selectIsmCustManageByPhonenumber(ismCustManage.getPhonenumber());
                if (StringUtils.isNull(u))
                {
                    BeanValidators.validateWithException(validator, ismCustManage);
                    //user.setPassword(SecurityUtils.encryptPassword(password));
                    ismCustManage.setFamilyIntegral(0L);
                    ismCustManage.setCreateBy(operName);
                    this.insertIsmCustManage(ismCustManage);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、姓名 " + ismCustManage.getPersonName() + "、手机号 " + ismCustManage.getPhonenumber() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    BeanValidators.validateWithException(validator, ismCustManage);
                    ismCustManage.setUpdateBy(operName);
                    this.updateIsmCustManageByPhonenumber(ismCustManage);
                    successNum++;
                    successMsg.append("<br/>" + successNum +"、姓名 " + ismCustManage.getPersonName() + "、手机号 " + ismCustManage.getPhonenumber() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、姓名 " + ismCustManage.getPersonName() + "、手机号 " + ismCustManage.getPhonenumber() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、姓名 " + ismCustManage.getPersonName() + "手机号 " + ismCustManage.getPhonenumber() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public IsmCustManage selectIsmCustManageByPhonenumber(String phonenumber) {
        return ismCustManageMapper.selectIsmCustManageByPhonenumber(phonenumber);
    }

    @Override
    public int updateIsmCustManageByPhonenumber(IsmCustManage ismCustManage) {
        return ismCustManageMapper.updateIsmCustManage(ismCustManage);
    }

    @Override
    public List<IsmCustManage> selectIsmCustIntegralList(IsmCustManage ismCustManage) {
        return ismCustManageMapper.selectIsmCustIntegralList(ismCustManage);
    }

    @Override
    public int updateIsmCustManageIntegral(IsmCustManage ismCustManage) {
        return ismCustManageMapper.updateIsmCustManageIntegral(ismCustManage);
    }

    @Override
    public List<IsmCustManage> selectIsmCustIntegralByfamilyInfo(IsmCustManage ismCustManage) {
        return ismCustManageMapper.selectIsmCustIntegralByfamilyInfo(ismCustManage);
    }

    @Override
    public String importCustIntegral(List<IsmCustManage> custManageList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(custManageList) || custManageList.size() == 0)
        {
            throw new ServiceException("导入客户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        //String password = configService.selectConfigByKey("sys.user.initPassword");
        for (IsmCustManage ismCustManage : custManageList)
        {
            try
            {
                List<IsmCustManage> list = ismCustManageMapper.selectIsmCustIntegralByfamilyInfo(ismCustManage);
                if (list.size()==1)
                {
                    BeanValidators.validateWithException(validator, ismCustManage);
                    String familySn = ismCustManage.getFamilySn();
                    String holderName = ismCustManage.getHouseholderName();
                    String remark = ismCustManage.getRemark();
                    long familyIntegralNew = ismCustManage.getFamilyIntegral();
                    IsmCustManage tmp = list.get(0);
                    long familyIntegralBefore = tmp.getFamilyIntegral();
                    long familyIntegralAfter = familyIntegralBefore + familyIntegralNew;
                    if(familyIntegralAfter<0){
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、家庭编号 " + ismCustManage.getFamilySn() + "、户主 " + ismCustManage.getHouseholderName() + " 登记失败");
                        continue;
                    }
                    IsmIntegralRecord ismIntegralRecord = new IsmIntegralRecord();
                    ismIntegralRecord.setFamilySn(familySn);
                    ismIntegralRecord.setHouseholderName(holderName);
                    ismIntegralRecord.setIntegralBefore(familyIntegralBefore);
                    ismIntegralRecord.setIntegralExchange(familyIntegralNew);
                    ismIntegralRecord.setIntegralAfter(familyIntegralAfter);
                    ismIntegralRecord.setCreateBy(operName);
                    ismIntegralRecord.setRemark(remark);
                    ismIntegralRecordMapper.insertIsmIntegralRecord(ismIntegralRecord);
                    ismCustManage.setFamilyIntegral(familyIntegralAfter);
                    ismCustManage.setCreateBy(operName);
                    this.updateIsmCustManageIntegral(ismCustManage);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、家庭编号 " + ismCustManage.getFamilySn() + "、户主 " + ismCustManage.getHouseholderName() + " 登记成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、家庭编号 " + ismCustManage.getFamilySn() + "、户主 " + ismCustManage.getHouseholderName() + " 登记失败");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、家庭编号" + ismCustManage.getFamilySn() + "、户主 " + ismCustManage.getHouseholderName() + " 登记失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，登记失败！共 " + failureNum + " 条数据，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部登记成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
